package drag2share;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class FilesServlet extends HttpServlet {

  private static final int MEGA = 1024 * 1024;

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Key key = KeyFactory.createKey("File", req.getPathInfo().substring(1));
    System.out.println(req.getPathInfo().substring(1));
    try {
      Entity file = ds.get(key);
      String fileName = file.getKey().getName();

      Blob blob = (Blob) file.getProperty("content");
      byte[] output = blob.getBytes();

      resp.setContentType(getMimeType(fileName));
      if(req.getParameter("download") != null)
        resp.setHeader("Content-Disposition", "attachment");
      ServletOutputStream out = resp.getOutputStream();
      out.write(output);

    } catch (EntityNotFoundException e) {
      e.printStackTrace();
    }
  }

  String getMimeType(String s) {
    s = s.substring(s.lastIndexOf('.') + 1);
    if (s.equals("txt") || s.equals("c") || s.equals("h") || s.equals("java") || s.equals("cpp"))
      s = "text/plain";
    else if (s.equals("png") || s.equals("jpeg") || s.equals("gif") || s.equals("jpg"))
      s = "image/" + ((!s.equals("jpeg")) ? s : "jpeg");
    else if (s.equals("pdf"))
      s = "application/pdf";
    else
      s = "application/octet-stream";
    return s;
  }

  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    byte[] input = new byte[MEGA];
    int len = req.getInputStream().read(input, 0, MEGA);
    byte[] temp = new byte[len];
    System.arraycopy(input, 0, temp, 0, len);
    Blob blob = new Blob(temp);
    Entity file = new Entity("File", req.getPathInfo().substring(1));
    file.setProperty("content", blob);
    ds.put(file);
  }
}
